import axios from 'axios';
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  AxiosRequestHeaders
} from 'axios';
import { useTokenStore } from '@/stores/token';
import router from '@/router';
import type { ApiResponse } from '@/types/user';

// 创建axios实例
const baseURL = 'http://localhost:8080/api';
const instance: AxiosInstance = axios.create({
  baseURL,
  timeout: 10000
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    const tokenStore = useTokenStore();
    if (tokenStore.token) {
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${tokenStore.token}`
      } as unknown as InternalAxiosRequestConfig['headers'];
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>): any => {
    const res = response.data;
    if (res.code === 200) {
      return res;
    }

    // 处理错误
    handleErrorResponse(res);
    return Promise.reject(res);
  },
  (error) => {
    if (error.response) {
      handleErrorResponse(error.response.data);
    } else {
      // 网络错误等
      console.error('网络连接异常');
    }
    return Promise.reject(error);
  }
);

// 处理错误响应
function handleErrorResponse(res: ApiResponse) {
  // 可以使用Element Plus的消息提示
  console.error(res.message || '请求失败');

  // 处理特定错误码
  if (res.code === 401) {
    // 未登录或token失效
    const tokenStore = useTokenStore();
    tokenStore.clearToken();
    router.push('/login');
  }
}

export default instance;
